home *** CD-ROM | disk | FTP | other *** search
/ Chip 2007 January, February, March & April / Chip-Cover-CD-2007-02.iso / Pakiet bezpieczenstwa / mini Pentoo LiveCD 2006.1 / mpentoo-2006.1.iso / livecd.squashfs / opt / pinstaller / XMLParser.py < prev   
Text File  |  2005-10-15  |  5KB  |  204 lines

  1. # Copyright 1999-2005 Gentoo Foundation
  2. # This source code is distributed under the terms of version 2 of the GNU
  3. # General Public License as published by the Free Software Foundation, a copy
  4. # of which can be found in the main directory of this project.
  5. import xml.sax, string, xml.dom.minidom
  6.  
  7. class XMLTag(object):
  8.  
  9.     def __init__(self, name=None, attr=None, children=None, contents=None):
  10.         self._tag = { 'name': "", 'attr': {}, 'children': [], 'contents': "" }
  11.         if name:
  12.             self.set_name(name)
  13.         if attr:
  14.             self.set_attrs(attr)
  15.         if children:
  16.             self.set_children(children)
  17.         if contents:
  18.             self.set_contents(contents)
  19.  
  20.     def get_name(self):
  21.         return self._tag['name']
  22.  
  23.     def set_name(self, name):
  24.         self._tag['name'] = name
  25.  
  26.     def get_attrs(self):
  27.         return self._tag['attr']
  28.  
  29.     def get_attr(self, attrname):
  30.         try:
  31.             return self._tag['attr'][attrname]
  32.         except KeyError:
  33.             return None
  34.  
  35.     def set_attr(self, attrname, attrvalue):
  36.         self._tag['attr'][attrname] = attrvalue
  37.  
  38.     def set_attrs(self, attr):
  39.         self._tag['attr'] = attr
  40.  
  41.     def del_attr(self, attrname):
  42.         del self._tag['attr'][attrname]
  43.  
  44.     def get_children(self):
  45.         return self._tag['children']
  46.  
  47.     def set_children(self, children):
  48.         self._tag['children'] = children
  49.  
  50.     def get_child(self, index):
  51.         return self._tag['children'][index]
  52.  
  53.     def add_child(self, child, index=-1):
  54.         if index == -1:
  55.             self._tag['children'].append(child)
  56.         else:
  57.             self._tag['children'].insert(child, index)
  58.  
  59.     def del_child(self, index):
  60.         del self._tag['children'][index]
  61.  
  62.     def get_contents(self):
  63.         return self._tag['contents']
  64.  
  65.     def set_contents(self, contents):
  66.         self._tag['contents'] = contents
  67.  
  68.     def xml(self, output_this_tag=True, make_pretty=False):
  69.         _xml = ""
  70.         if output_this_tag:
  71.             _xml += "<" + self.get_name()
  72.             tag_attrs = self.get_attrs()
  73.             if tag_attrs:
  74.                 sorted_attrs = tag_attrs.keys()
  75.                 sorted_attrs.sort()
  76.                 for attr in sorted_attrs:
  77.                     _xml += " " + attr + '="' + tag_attrs[attr] + '"'
  78.             _xml += ">"
  79.             for child in self.get_children():
  80.                 _xml += child.xml()
  81.             _xml += self.get_contents() + "</" + self.get_name() + ">"
  82.         else:
  83.             for child in self.get_children():
  84.                 _xml += child.xml()
  85.         if make_pretty:
  86.             dom = xml.dom.minidom.parseString(_xml)
  87.             return dom.toprettyxml()
  88.         else:
  89.             return _xml
  90.  
  91.     def get_value(self, path):
  92.         pathlist = path.split(".")
  93.         if not path:
  94.             return self.get_contents()
  95.         if len(pathlist) == 1:
  96.             if pathlist[0] in self.get_attrs():
  97.                 return self.get_attrs()[path]
  98.         for child in self.get_children():
  99.             if child.get_name() == pathlist[0]:
  100.                 return child.get_value(".".join(pathlist[1:]))
  101.         return None
  102.  
  103.     def get_tag(self, path):
  104.         pathlist = path.split(".")
  105.         if len(pathlist) == 1:
  106.             for child in self.get_children():
  107.                 if child.get_name() == path:
  108.                     return child
  109.             return None
  110.         else:
  111.             for child in self.get_children():
  112.                 if child.get_name() == pathlist[0]:
  113.                     return child.get_tag(".".join(pathlist[1:]))
  114.             return None
  115.  
  116.     def set_value(self, path, value):
  117.         pathlist = path.split(".")
  118.         if not path:
  119.             self.set_contents(value)
  120.             return True
  121.         if len(pathlist) == 1:
  122.             if pathlist[0] in self.get_attrs():
  123.                 self.get_attrs()[path] = value
  124.                 return True
  125.         for child in self.get_children():
  126.             if child.get_name() == pathlist[0]:
  127.                 return child.set_value(".".join(pathlist[1:]), value)
  128.         return False
  129.  
  130.     def __getitem__(self, item):
  131.         return self.get_value(item)
  132.  
  133.     def __setitem__(self, item, value):
  134.         return self.set_value(item, value)
  135.  
  136.     name = property(get_name, set_name)
  137.     attr = property(get_attrs, set_attrs)
  138.     children = property(get_children, set_children)
  139.     contents = property(get_contents, set_contents)
  140.  
  141. class XMLParser(xml.sax.ContentHandler, XMLTag):
  142.  
  143.     def __init__(self, file=None):
  144.         XMLTag.__init__(self, name="__top__")
  145.         self._xml_elements = []
  146.         self._xml_attrs = []
  147.         self._xml_current_data = ""
  148.         self._xml_tags = [self]
  149.         self._path = file
  150.  
  151.     def startElement(self, name, attr): 
  152.         """
  153.         XML SAX start element handler
  154.  
  155.         Called when the SAX parser encounters an XML opening element.
  156.         """
  157.  
  158.         self._xml_elements.append(name)
  159.         self._xml_attrs.append(attr)
  160.         self._xml_current_data = ""
  161.         self._xml_tags.append(XMLTag(name=name, attr=dict(attr)))
  162.         self._xml_tags[-2].add_child(self._xml_tags[-1])
  163.  
  164.     def endElement(self, name):
  165.         path = self._xml_element_path()
  166.  
  167.         if self._xml_current_data:
  168.             self._xml_tags[-1].set_contents(self._xml_current_data)
  169.  
  170.         # Keep the XML state
  171.         self._xml_current_data = ""
  172.         self._xml_attrs.pop()
  173.         self._xml_elements.pop()
  174.         self._xml_tags.pop()
  175.  
  176.     def characters(self, data):
  177.         """
  178.         XML SAX character data handler
  179.  
  180.         Called when the SAX parser encounters character data.
  181.         """
  182.  
  183.         self._xml_current_data += data.strip()
  184.  
  185.     def _xml_element_path(self):
  186.         """
  187.         Return path to current XML node
  188.         """                
  189.         return string.join(self._xml_elements, '/')
  190.  
  191.     def parse(self, path=None):
  192.         """
  193.         Parse serialized configuration file.
  194.         """
  195.         if path == None and self._path == None:
  196.             raise GLIException("NoFileGiven",'fatal', 'parse', "You must specify a file to parse!")
  197.         elif path == None:       
  198.             xml.sax.parse(self._path, self)
  199.         else:
  200.             xml.sax.parse(path, self)
  201.  
  202.     def serialize(self):
  203.         return self.xml(output_this_tag=False, make_pretty=True)
  204.